import 'dart:async';

import 'package:flutter/material.dart';
import 'package:mi_mang_flutter/api/email_api.dart';
import 'package:mi_mang_flutter/page/setting/account/verification_code_util.dart';
import 'package:mi_mang_flutter/page/setting/setting_router.dart';
import 'package:mi_mang_flutter/provider/user_provider.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/routers/fluro_navigator.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'package:provider/provider.dart';

class VerificationCodePage extends StatefulWidget {
  /// 邮箱
  final String? email;

  VerificationCodePage({
    Key? key,
    this.email,
  }) : super(key: key);

  @override
  _VerificationCodePageState createState() => _VerificationCodePageState();
}

class _VerificationCodePageState extends State<VerificationCodePage> {
  /// 倒计时秒数
  final int _second = 60;

  Timer? _timer;

  /// 当前秒数
  late int _currentSecond;
  bool _isClick = true;

  List<String> _codeList = List.filled(6, '', growable: false);

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Consumer<UserProvider>(builder: (context, provider, _) {
        return Padding(
          padding: EdgeInsets.symmetric(horizontal: 30.0, vertical: 30.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Text(
                '输入验证码',
                style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
              ),
              Gaps.vGap15,
              Text(
                '我们已向 ${widget.email} 发送了一个六位验证码',
                style: TextStyle(
                  color: Colors.grey,
                ),
              ),
              Gaps.vGap15,
              VerificationCodeUtil(
                codeList: _codeList,
                onChanged: (v) {
                  for (int i = 0; i < _codeList.length; i++) {
                    if (i < v.length) {
                      _codeList[i] = v.substring(i, i + 1);
                    } else {
                      _codeList[i] = '';
                    }
                  }
                  setState(() {});
                },
              ),
              Gaps.vGap15,
              Container(
                width: double.infinity,
                height: 48.0,
                child: TextButton(
                  child: Text(
                    _isClick ? '重新获取' : '已发送($_currentSecond s)',
                    style: TextStyle(fontSize: 18.0, color: Colors.black),
                  ),
                  onPressed: _isClick
                      ? () {
                          EmailApi.sendEmailCode(widget.email).then((val) {});
                          setState(() {
                            _currentSecond = _second;
                            _isClick = false;
                          });
                          _timer =
                              Timer.periodic(Duration(seconds: 1), (timer) {
                            setState(() {
                              _currentSecond = _second - timer.tick;
                              _isClick = _currentSecond < 1;
                              if (_isClick) {
                                _cancelTimer();
                              }
                            });
                          });
                        }
                      : null,
                ),
              ),
              Gaps.vGap25,
              ElevatedButton(
                onPressed: () {
                  _bindEmail(provider);
                },
                child: Container(
                  height: 45,
                  width: double.infinity,
                  alignment: Alignment.center,
                  child: Text(i18n(context).next),
                ),
              ),
            ],
          ),
        );
      }),
    );
  }

  /// 账号绑定邮箱
  void _bindEmail(UserProvider provider) {
    EmailApi.bindEmail(_codeList.join().trim(), widget.email).then((val) {
      provider.init();
      NavigatorUtils.push(
        context,
        "${SettingRouter.account}",
        replace: true,
      );
    });
  }

  @override
  void dispose() {
    _cancelTimer();
    super.dispose();
  }

  /// 取消倒计时的计时器。
  void _cancelTimer() {
    _timer?.cancel();
    _timer = null;
  }
}
